/*
Realistic Unit Modification v4.0 Dialog 
v4.0.0.1 [ALPHA]
Concept & Development by Draper & Raps | [VRC]
*/

/* variables defined */
_arry = _this select 0;
varSaveArray = _arry;
+varSaveArray;
_payload = _this select 1;
_payloadtype = _this select 2;

_heloname = _arry select 0;
_helo = _arry select 0;
_callsign = _arry select 1;
_heloclass = _arry select 2;
_spwn = _arry select 3;
_heloarr = _arry;

_paycallsign = _payload select 0;
_class = _payload select 1;
_init = _payload select 2;
_payloadWeight = _payload select 3;

rumLZPos = nil;
_cont = format ["%1",_helo];
_end = format ["%1",_helo];
_vehCrew = [];
_crewCount = nil;
_crew = [];

varRUM_MissionType = _payloadtype;
RUM_THEL_AbortRTB = false;
RUM_SUP_flyHeightVar = nil;
RUM_Abort = nil;
RUM_THel_endflight = nil;
RUM_THel_land = nil;
_wpArray = [];

// if (_helo getVariable "RUM_inFlight") exitWith {hint "Helo in flight";};

/////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////// Start of Map selection /////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
RUM_ASclick = false;

openMap [true,false];
for [{_n = 1},{_n <= 3},{_n = _n + 1}] do {
	_mkrname = "";
	_type = "";
	_hint = "";
	switch (_n) do {
		case 1: {
			_mkrname = format ["%1target",_helo];
			_type = "mil_pickup";
			_hint = "Select Drop-Off LZ";
		};
		case 2: {
			_mkrname = format ["%1ingress",_helo];
			_type = "mil_start";
			_hint = "Select Drop-Off LZ Ingress Point";
		};
		case 3: {
			_mkrname = format ["%1egress",_helo];
			_type = "mil_end";
			_hint = "Select Drop-Off LZ Egress Point";
		};
		default {
			hint "shit";	
		};
	};

	_asloc = createMarkerLocal [_mkrname, [0,0,0]];
	_asloc setMarkerShapeLocal "ICON";
	_mkrname setMarkerTypeLocal _type;
	_mkrname setMarkerAlphaLocal .35;
	
	_mapclick = ["rum_mapclick_id", "onMapSingleClick", { _this setMarkerPosLocal _pos;RUM_ASclick = true; }, _mkrname] call BIS_fnc_addStackedEventHandler;
	
	titleText [_hint, "PLAIN DOWN"];
	
	waitUntil {
		(RUM_ASclick || !(visiblemap))
	};
	
	if (!visibleMap) exitWith {
		RUM_Abort = true;
		systemChat "Insert Operation Aborted";
		_stgtar = nil;
		_mapclick = ["rum_mapclick_id", "onMapSingleClick"] call BIS_fnc_removeStackedEventHandler;
		RUM_ASclick = false;
		/* delete all the markers that were created for this instance. */
		_mkrname1 = format ["%1ingress",_helo];
		_mkrname2 = format ["%1target",_helo];
		_mkrname3 = format ["%1egress",_helo];
		_mkrname4 = format ["%1ingress2",_helo];
		_mkrname5 = format ["%1target2",_helo];
		_mkrname6 = format ["%1egress2",_helo];
		deletemarkerLocal _mkrname1;
		deletemarkerLocal _mkrname2;
		deletemarkerLocal _mkrname3;
		deletemarkerLocal _mkrname4;
		deletemarkerLocal _mkrname5;
		deletemarkerLocal _mkrname6;
		RUM_SUPAircraft_Spawn = RUM_SUPAircraft_Spawn + [_arry];
		_helo setVariable ["RUM_inFlight", false, true];
	};
	
	/* Create and array of the markers to manage when needed */
	_wpArray = _wpArray + [_mkrname];

	if((_n == 2) || (_n == 3)) then {
		_mkrname2 = format ["%1target",_helo];
		_mkrname setMarkerDirLocal ((getMarkerPos _mkrname2 select 0)-(getMarkerPos _mkrname select 0)) atan2 ((getMarkerPos _mkrname2 select 1)-(getMarkerPos _mkrname select 1));
	};
	_mapclick = ["rum_mapclick_id", "onMapSingleClick"] call BIS_fnc_removeStackedEventHandler;
	RUM_ASclick = false;
};

/* define waypoint locations */
// _wpPos1 = getPos _egress;
_wpPos2 = getMarkerPos format ["%1ingress",_helo];
_wpPos3 = getMarkerPos format ["%1target",_helo];
_wpPos4 = getMarkerPos format ["%1egress",_helo];
// _wpPos5 = getPos _ingress;
_wpPos6 = getPos _spwn;

titleFadeOut 0;
sleep 1;
openMap [false,false];

/////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////// Start of Helo Setup //////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////

// player sidechat format["Array: %1",_arry];
/**/

if (!("plane" in _heloarr)) then {
	if ((_payloadWeight >= RUM_SUP_payloadMedHeloLimit)) then {
			_heloclass = "B_Heli_Transport_03_unarmed_F"; // this will be the default if the aircraft is to small
		} else {
	_heloclass = _heloclass;
	};
	if ((_payloadWeight <= RUM_SUP_payloadParaLimit)) then {
			_payloadtype = "Para Drop"; 
		} else {
	_payloadtype = _payloadtype;
	};
};
_homedir = getdir _spwn;
_helo = createVehicle [_heloclass, getPos _spwn, [], 0, "FLY"];


if ("plane" in _heloarr) then {
	RUM_SUP_flyHeightVar = (RUM_SUP_flyHeightPLN);
};

_helo setpos [(getpos _spwn select 0),(getpos _spwn select 1),(getpos _spwn select 2)+RUM_SUP_flyHeightVar];
_helo setdir _homedir;
_helo setVariable ["RUM_inFlight", true, true];

/* Unlocks the vehicle positions */
_helo lockDriver false; // Pilot
_helo lockTurret [[0], false]; // Co-Pilot
_helo lockTurret [[1], false]; // Gunner1 - if the vehicle has this position
_helo lockTurret [[2], false]; // Gunner2 - if the vehicle has this position

/* create units to fly helo  */
_grp = createGroup side player;
_pilot = _grp createUnit [RUM_THEL_Pilot, getpos _spwn, [], 15, "NONE"];
_commander = _grp createUnit [RUM_THEL_Pilot, getpos _spwn, [], 15, "NONE"];
_gunner1 = _grp createUnit [RUM_THEL_Pilot, getpos _spwn, [], 15, "NONE"];
_gunner2 = _grp createUnit [RUM_THEL_Pilot, getpos _spwn, [], 15, "NONE"];

/* count turret positions */
_cfg = configFile >> "CfgVehicles" >> typeof _helo >> "turrets";

_pilot moveInDriver _helo;
_commander moveinTurret [_helo,[0]];
_gunner1 moveinTurret [_helo,[1]];
_gunner2 moveinTurret [_helo,[2]];

if (count _cfg <= 1) then {
	deleteVehicle _gunner1;
	deleteVehicle _gunner2;
};

/* AI Crew Optimization */
{
	// _x disableAi "FSM";
	// _x disableAi "TARGET";
	// _x disableAi "AUTOTARGET";
	_x setSkill 1;
} forEach units _grp;

/* disables AI programming for VCOM AI */
{
	_x setVariable ["NOAI",1,false];
} forEach (units _grp);

/* Over Water Check - For Carrier Bases */
if (surfaceIsWater (getpos _spwn)) then {

	/* something here - WIP */
};

/* vehicle specific features */
_vehOptions = [_helo] spawn FNC_H_rumVehicleOptions;

/////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Start of Supply ///////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
if ("plane" in _heloarr) then {
	_helo flyInHeight RUM_SUP_flyHeightPLN;

	// set velocity of plane
	_vel = velocity _helo;
	_dir = direction _helo;
	_speed = 200;
	_helo setVelocity [(_vel select 0)+(sin _dir * _speed),(_vel select 1)+(cos _dir * _speed),(_vel select 2)];
};

if (_payloadtype == "Sling Load") then {
	_dropitem = createVehicle [_class, [0,0,0], [], 0, "NONE"];
	sleep 0.125;
	_helo setSlingLoad _dropitem;
	[_dropitem, _init] call compile preprocessFile (RUM_PATH+"Supply\A3_SupplyLoads.sqf");

	["sling",[player,_pilot,_callsign,_paycallsign]] execVM (RUM_PATH+"Supply\radiodialogs.sqf");
} else {
	["para",[player,_pilot,_callsign,_paycallsign]] execVM (RUM_PATH+"Supply\radiodialogs.sqf");
};

sleep random(10);


/* locks the vehicle positions so that other units cannot get in them */
_helo lockDriver true; // Pilot
_helo lockTurret [[0], true]; // Co-Pilot
_helo lockTurret [[1], true]; // Gunner1 - if the vehicle has this position
_helo lockTurret [[2], true]; // Gunner2 - if the vehicle has this position

/* store crew count for use in other scripts/mission types */
_crewCount = (count units _helo);
_vehCrew = (units _helo);
_vehGroup = group _helo;

/* setup variable for helo crew to be used in other functions */
_helo setVariable ["_crewVariables",[_crewCount,_vehCrew],true];

/* Build waypoints and sets helo movement */
// [_helo,_grp,_wpPos1] call FNC_H_rumTakeOff;
[_helo,_grp,_wpPos2] call FNC_H_rumMoveWP;
	
if (_payloadtype == "Sling Load") then {
	_height = 12;
	
	[_helo,_grp,_wpPos3] call FNC_H_rumUnhookCargo;
	
	waitUntil {
		sleep 0.125;
		if (_helo distance _wpPos3 < 175) then {
			true;
		};
	};

	// _helo flyInHeight _height;

	waitUntil{
		sleep 0.0015;
		((!alive _helo) || (getposATL _helo select 2 <= _height) || (getposASL _helo select 2 <= _height));
	};
	{
		ropeCut [_x, 6];
		sleep 0.125;
	} forEach (ropes _helo);
		
	sleep 1.5;
	// detach _dropitem;
	// _dropitem setPos [getpos _dropitem select 0, getpos _dropitem select 1,0];
	// _helo setvariable ["lift",false,true];
	_helo FlyInHeight RUM_SUP_flyHeight;
} else {
	[_helo,_grp,_wpPos3] call FNC_H_rumMoveDropWP;
	if !("plane" in _heloarr) then {
		[_helo,_grp,_wpPos4] call FNC_H_rumMoveWP;
	};

	waitUntil {
		sleep 0.125;
		if (_helo distance _wpPos3 < 200) then {
			true;
		};
	};
	_heloDropPos = getPos _helo;
	_heloDropDir = getDir _helo;
	_droppos = [(_heloDropPos select 0) - (15 * sin(_heloDropDir)), (_heloDropPos select 1) - (15 * cos(_heloDropDir)), (_heloDropPos select 2)];
	_dropitem = createVehicle [_class, _droppos, [], 0, "NONE"];
	[_dropitem, _init] call compile preprocessFile (RUM_PATH+"Supply\A3_SupplyLoads.sqf");
	
	_chute = "B_Parachute_02_F" createVehicle _droppos;
	_chute setPos _droppos;
	_chute allowDamage false;

	// create smoke or IR on chute for tracking while in flight - IR will be visable on the ground as well.
	private ["_marker","_markType"];
	_dayTime = daytime;
	
	if ((_dayTime < 18) && (_dayTime > 6)) then {
		_markType = "SmokeShellBlue";
	} else {
		_markType = "NVG_TargetC";
	};

	_marker = _markType createVehicle position _dropitem;
	_marker setPosATL (getPosATL _dropitem);
	_marker attachTo [_dropitem,[0,0,1]];
	
	_dropitem attachTo [_chute,[0,0,0]];
	_chute setVelocity velocity _helo;
	
	if (_helo iskindof "Plane") then {
		_helo FlyInHeight RUM_SUP_flyHeightPLN;
	} else {
		_helo FlyInHeight RUM_SUP_flyHeight;
	};
	[_dropitem, _chute, _marker] spawn {
		_dropitem = _this select 0;
		_chute = _this select 1;
		_marker = _this select 2;
		
		// Waiting till on ground
		waitUntil{
			sleep 0.015;
			(getPosATL _dropitem select 2 < 2);
		};
		detach _dropitem;
		detach _marker;
		sleep 0.3;
		
		_dropitem setPosATL [(getPosATL _dropitem select 0),(getPosATL _dropitem select 1),0.1];
		_marker setPosATL [(getPosATL _dropitem select 0) + 1,(getPosATL _dropitem select 1) + 1,0.1];

		// adds green smoke for when the object has landed
		if (RUM_SUP_smoke) then {
			"SmokeShellGreen" createVehicle (getpos _dropitem);
		};
		
		// Enable R3F compatibility
		_dropitem setVariable ["R3F_LOG_disabled", false];
		
		// Assign a numbered ID to the dropped item for use in persistant data bases
		_id = 1000 + ceil(random(9000));
		_name = format["RUM_log_%1",_id];
		_dropitem setVariable ["pdb_save_name", _name, true];
	};
};
	
/* generate waypoints for the helop */
// [_helo,_grp,_wpPos5] call FNC_H_rumMoveWP;
if (_payloadtype == "Sling Load") then {
	[_helo,_grp,_wpPos4] call FNC_H_rumDustOff;
};
[_helo,_grp,_wpPos6] call FNC_H_rumSpawn;

/* end of flight check when helo has landed */
waitUntil{
	sleep 0.15;
	((!alive _helo) or (((((getPos _helo select 0) - (getpos _spwn select 0))^2+((getPos _helo select 1) - (getpos _spwn select 1))^2)^0.5) <= 300));
};

if (!alive _helo) exitwith {[_helo,_spwn,_pilot,_wpArray] call FNC_H_rumEndMissionSpawn;};

/* calls cleanup function once helo has returned to base */
[_helo,_spwn,_pilot,_wpArray] call FNC_H_rumEndMissionSpawn;

/* Terminate spawn for vehicle options */
terminate _vehOptions;

/* waits till crew are deleted */
waitUntil {
	sleep 0.5;
	(!alive _helo || ((_helo getVariable ["_crewVariables",[]] select 0) == 0));
};

if (!alive _helo) exitwith {};

hintSilent "";
_helo setVariable ["_crewVariables",nil];
_helo addEventHandler ["HandleDamage", {true}];

sleep RUM_SUP_ReSupTime;

RUM_SUPAircraft_Spawn = RUM_SUPAircraft_Spawn + [_arry];
_helo setVariable ["RUM_inFlight", false, true];

/////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////// End of Supply //////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////

// exit script
if (true) exitwith {};
